/*
 * File Name：BookcaseGridVAdapter.java
 * Copyright：Copyright 2008-2015 CiWong.Inc. All Rights Reserved.
 * Description： BookcaseGridVAdapter.java
 * Modify By：res-dlzhou
 * Modify Date：2015年3月9日
 * Modify Type：Add
 */
package com.ciwong.epaper.modules.epaper.adapter;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.widget.CWToast;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseIntentFlag;
import com.ciwong.mobilelib.widget.CWDialog;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;

import java.io.Serializable;
import java.util.List;

/**
 * 书柜书籍适配器
 */
public class BookAdapter extends BaseAdapter {
    private Activity activity;

    private List<EpaperInfo> epaperInfos;


    private int bWidth, bHeight, tHeight, space;

    public List<EpaperInfo> getEpaperInfos() {
        return epaperInfos;

    }

//    private List<EpaperInfo> deletedEInfoList = new ArrayList<EpaperInfo>();

    /**
     * 构造函数
     *
     * @param activity    上下文
     * @param epaperInfos 电子报信息
     */
    public BookAdapter(Activity activity, List<EpaperInfo> epaperInfos, int bookWidth, int bookHeight) {
        this.activity = activity;
        this.epaperInfos = epaperInfos;
        this.bWidth = bookWidth;
        this.bHeight = bookHeight;
    }

    @Override
    public int getCount() {
        return epaperInfos == null ? 0 : epaperInfos.size();
    }

    @Override
    public Object getItem(int position) {
        return epaperInfos == null ? null : epaperInfos.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private class ViewHolder {
        private SimpleDraweeView bookIcon;

        private TextView bookTitle;

        private View delBook;

        private ImageView kaoShi;

    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = View.inflate(activity, R.layout.item_book, null);
            holder.bookIcon = (SimpleDraweeView) convertView.findViewById(R.id.item_book_icon);

            holder.bookTitle = (TextView) convertView
                    .findViewById(R.id.item_book_title);
            holder.delBook = convertView.findViewById(R.id.icon_delete_book);
            holder.kaoShi= (ImageView)convertView.findViewById(R.id.kao_shi);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if (epaperInfos != null && !epaperInfos.isEmpty()
                && position < epaperInfos.size()) {
            final EpaperInfo epaperInfo = epaperInfos.get(position);

            holder.kaoShi.setVisibility(epaperInfo.getRequired()==1?View.VISIBLE:View.GONE);
//             ViewGroup.LayoutParams params= holder.bookIcon.getLayoutParams();

            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.bookIcon.getLayoutParams();

        Log.d("layoutParams", "#####bWidth######"+bWidth);
        Log.d("layoutParams", "#####bHeight######"+bHeight);
            params.width = bWidth;
            params.height = bHeight;
            holder.bookIcon.setLayoutParams(params);

//            ImageLoader.getInstance().displayImage(epaperInfo.getCover(),
//                    new ImageViewAware(holder.bookIcon),
//                    EConstants.getBookCoverOption());

            if (!TextUtils.isEmpty(epaperInfo.getCover())) {
                Uri  uri = Uri.parse(epaperInfo.getCover());
                holder.bookIcon.setImageURI(uri);
            }else {
                setLocalDefaultImg( holder.bookIcon);
            }

            holder.bookTitle.setText(epaperInfo.getProductName());

            holder.bookIcon.setBackgroundResource(0);

            holder.delBook.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (getCount() == 1) {
                        ((BaseActivity) activity)
                                .showToastAlert(R.string.exist_one_book);
                        return;
                    }

                    CWDialog dialog = new CWDialog(activity);
                    dialog.setMessage(
                            activity.getString(R.string.confirm_delete_book,
                                    epaperInfo.getProductName()));
                    dialog.setNegativeButton(android.R.string.cancel, null);
                    dialog.setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (NetworkUtils.isOnline()) {
                                        //向服务器上传删除书籍记录
                                        setDelBookcase(epaperInfo);
                                    } else {
                                        CWToast.makeText(activity,
                                                R.string.connect_disable, Toast.LENGTH_LONG,
                                                true).setToastType(CWToast.TOAST_TYPE_ERROR)
                                                .show();

                                    }
                                    dialog.dismiss();
                                }
                            });
                    dialog.show();
                }
            });
        }

        return convertView;
    }

    /**
     * 获取保存的书籍ID的KEY
     *
     * @return
     */
    private String getSaveBookIdKey() {
        return SerializableManager.SerializeKey.SHARE_KEY_BOOK_ID
                + SerializableManager.getInstance().getUserId(true);
    }

    /**
     * 删除书柜记录By书箱ID
     */
    public void setDelBookcase(final EpaperInfo epaperInfo) {
        ((BaseActivity) activity).showCricleProgress();
        EpaperDao.getInstance().setDelBookcaseToServer(EApplication.BRAND_ID, epaperInfo.getProductId(), epaperInfo.getServer().getId(), new BaseExtCallBack(activity,EApplication.getInstance().getUserInfoBase().getUserId()+"") {



            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode,data);
                CWLog.e("TAT", "setDelBookcase 上传失败");
                ((BaseActivity) activity).hideCricleProgress();
            }

            @Override
            public void failed(Object data) {
                CWLog.e("TAT", "setDelBookcase 上传失败");
               super.failed(data);
                ((BaseActivity) activity).hideCricleProgress();
            }

            @Override
            public void success(Object data) {
                CWLog.e("TAT", "setDelBookcase  上传成功");
                epaperInfos.remove(epaperInfo);
                String bookId = CWSys
                        .getSharedString(getSaveBookIdKey(), null);
                if (epaperInfo.getPackageId().equals(bookId)) {// 删除的是当前选中的书
                    CWSys.setSharedString(getSaveBookIdKey(), null);
                }
                epaperInfo.setAdded(false);
//                deletedEInfoList.add(epaperInfo);
                notifyDataSetChanged();

                Intent intent = new Intent();
                intent.putExtra(BaseIntentFlag.INTENT_FLAG_OBJ_LIST, (Serializable) epaperInfos);
                activity.setResult(Activity.RESULT_OK, intent);
                ((BaseActivity) activity).hideCricleProgress();
            }
        });
    }

    private void setLocalDefaultImg(SimpleDraweeView simpleDraweeView) {
        Uri uri = Uri.parse("res:///" + R.mipmap.item_load_icon);
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setUri(uri)
                .setTapToRetryEnabled(true)
                .build();
        simpleDraweeView.setController(controller);
    }
}
